<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-icon><PieChart /></el-icon>
        <span>今日日志等级分布</span>
      </div>
    </template>
    <div class="chart-container">
      <div ref="chartContainer" class="echart-container"></div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { PieChart } from '@element-plus/icons-vue'
import { useECharts } from '@/composables/useECharts'
import useApiStore from '@/core/apiStore'

const apiStore = useApiStore()

const chartContainer = ref<HTMLElement | null>(null)
const { setOptions } = useECharts(chartContainer)

const logLevels = ['INFO', 'WARNING', 'ERROR', 'UNKNOWN']

const getChartData = (data: { count: number; log_level: string }[]) => {
  const levelMap = new Map<string, number>()
  logLevels.forEach(level => levelMap.set(level, 0))
  const { distributions = [] } = data

  distributions.forEach(item => {
    if (levelMap.has(item.log_level)) {
      levelMap.set(item.log_level, item.count)
    }
  })

  return Array.from(levelMap).map(([name, value]) => ({
    value,
    name,
    itemStyle: {
      color:
        name === 'INFO'
          ? '#4361ee'
          : name === 'WARNING'
            ? '#ffd166'
            : name === 'ERROR'
              ? '#ef476f'
              : '#6c757d',
    },
  }))
}

watch(apiStore.apiStates.todayLevelDistribution, newVal => {
  if (newVal.data?.data) {
    const chartData = getChartData(newVal.data.data)
    setOptions({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(0,0,0,0.7)',
        padding: 10,
      },
      legend: {
        orient: 'horizontal',
        bottom: 0,
        data: logLevels,
        itemGap: 20,
        itemWidth: 8,
        itemHeight: 8,
      },
      series: [
        {
          name: '日志等级',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 4,
            borderColor: '#fff',
            borderWidth: 1,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: chartData,
        },
      ],
    })
  }
})
</script>

<style lang="scss" scoped>
.chart-container {
  position: relative;
  height: 250px;
  width: 100%;

  .echart-container {
    width: 100%;
    height: 100%;
  }
}
</style>
